<style scoped src="./index.scss" lang="scss" rel="stylesheet/scss"></style>
<template src="./index.html"></template>
<script>
import selectPower from "../selectPower/index.js";
export default {
  mixins: [Vue.prototype.$vFN.Mixins.Base, Vue.prototype.$vFN.Mixins.Edit],
  components: {
    SelectDataGoods: async () =>
      Vue.extend(await Vue.prototype.$vFN.Components.Base.SelectDataGoods()),
  },
  data() {
    return {
      appWindow: window,
      dialogTitle: "",

      form: {
        name: "", //等级名称
        remark: "", //等级描述
        grade: 1, // 等级权重

        isOpenRight: 0, //是否开启会员权益
        isCondition: 0, //是否同时满足
        conditionNode: 1, //条件节点

        // 关注公众号
        subscribeWeChatMp: {
          isSelect: 0,
          conditionValue: "",
        },

        // 购买指定商品
        buyProduct: {
          isSelect: 0,
          conditionValue: [],
        },

        // 消费次数
        consumeCount: {
          isSelect: 0,
          conditionValue: "",
        },

        // 消费金额
        consumeAmount: {
          isSelect: 0,
          conditionValue: "",
        },

        // 充值次数
        rechargeCount: {
          isSelect: 0,
          conditionValue: "",
        },

        // 充值金额
        rechargeAmount: {
          isSelect: 0,
          conditionValue: "",
        },
      },

      rightRuleIdLst: [], //权益id数组  发送数据需要

      ruleInfoList: [], //已选择的权益的名称数组    显示用

      goodsIds: [], //选择的商品的id数组

      gradeList: [
        { name: "一级", num: 1 },
        { name: "二级", num: 2 },
        { name: "三级", num: 3 },
        { name: "四级", num: 4 },
        { name: "五级", num: 5 },
        { name: "六级", num: 6 },
        { name: "七级", num: 7 },
        { name: "八级", num: 8 },
        { name: "九级", num: 9 },
        { name: "十级", num: 10 },
      ],

      apiUrl: {
        create: "mall-site-portal/member-level/create",
        detail: "mall-site-portal/member-level/getItem",
        update: "mall-site-portal/member-level/update",
        arr: "mall-site-portal/member-level/getRightsRuleByIds",
      },

      loading: true, //加载中
    };
  },
  watch: {
    goodsIds: {
      handler(newVal, oldVal) {
        this.form.buyProduct.conditionValue = newVal;
      },
    },
  },
  methods: {
    init() {
      // console.log(this.isDefault); //从home传来
      this.mixinEdit_editVisible = true;
    },

    // 选择权重
    selectGrade(num) {
      this.form.grade = num;
    },

    // 选择权益
    selectPower() {
      selectPower.init({
        ruleInfoList: this.ruleInfoList,
        onSuccess: (res) => {
          console.log("res", res); //返回一个数组
          this.rightRuleIdLst = []; //返回后，将原来id数组清空

          res.forEach((item) => {
            this.rightRuleIdLst.push(item.id);
          });

          console.log(this.rightRuleIdLst);

          if (this.rightRuleIdLst.length === 0) {
            this.ruleInfoList = [];
            return;
          }

          this.getRule();
        },
      });
    },

    // 取消
    cancel() {
      this.mixinEdit_editVisible = false;
    },
    // 提交
    async submit() {
      if (!(await this.validate())) {
        return;
      }

      const {
        name,
        remark,
        grade,
        isOpenRight,
        isCondition,
        conditionNode,
        subscribeWeChatMp,
        buyProduct,
        consumeCount,
        consumeAmount,
        rechargeCount,
        rechargeAmount,
      } = this.form;

      // 如果选了开启权益 而且权益数组为空
      if (isOpenRight === 1 && this.$vFN.Utils.isEmpty(this.rightRuleIdLst)) {
        this.$vFN.Tools.messageError("至少选择一项权益");

        return;
      }

      // 如果选了购买指定商品  但是没有选择商品
      if (
        buyProduct.isSelect === 1 &&
        this.$vFN.Utils.isEmpty(buyProduct.conditionValue)
      ) {
        this.$vFN.Tools.messageError("至少选择一项商品");
        return;
      }

      this.loading = true;

      let dataObj = {
        name,
        remark,
        grade,
        isOpenRight,
        isCondition,
        conditionNode,
        levelCondition: {
          subscribeWeChatMp,
          buyProduct,
          consumeCount,
          consumeAmount,
          rechargeCount,
          rechargeAmount,
        },
        rightRuleIdLst: this.rightRuleIdLst,
      };

      // 判断是新建还是修改
      let _url = "";
      if (this.type === "create") {
        _url = this.apiUrl.create;
      } else {
        _url = this.apiUrl.update;
        dataObj.id = this.id; //从home传来
      }

      let res = await this.$vFN.Http.post(
        {
          url: _url,
          data: dataObj,
        },
        window
      );
      this.loading = false;
      if (res._ok) {
        this.$vFN.Tools.messageSuccess(res.message);

        this.onSuccess();
        this.mixinEdit_editVisible = false;
      }
    },
    // 获取详情
    async getDetail() {
      let res = await this.$vFN.Http.post(
        {
          url: this.apiUrl.detail,
          data: {
            id: this.id, //从home页传来
          },
        },
        window
      );

      if (res._ok) {
        console.log("res", res.data);
        let data_ = res.data;

        for (const key in this.form) {
          if (!this.$vFN.Utils.isEmpty(data_[key])) {
            this.form[key] = data_[key];
          }
        }

        const { levelCondition, rightRuleIdLst } = data_;

        for (const key in levelCondition) {
          if (!this.$vFN.Utils.isEmpty(levelCondition[key])) {
            this.form[key] = levelCondition[key];
          }
        }

        this.rightRuleIdLst = rightRuleIdLst;

        console.log(" this.rightRuleIdLst", this.rightRuleIdLst);
        // console.error(this.rightRuleIdLst);
        // 查询权益规则数组
        if (rightRuleIdLst.length !== 0) {
          await this.getRule();
        }

        this.goodsIds = this.form.buyProduct.conditionValue;

        this.loading = false;
      }
    },

    // 查询权益规则数组
    async getRule() {
      let res = await this.$vFN.Http.post(
        {
          url: this.apiUrl.arr,
          data: {
            rightRuleIdLst: this.rightRuleIdLst, //从home页传来
          },
        },
        window
      );

      if (res._ok) {
        // 反转数组 添加的时候排后面
        this.ruleInfoList = res.data.reverse();

        // map处理数组
        this.ruleInfoList = this.ruleInfoList.map((item) => {
          return {
            id: item.id,
            rightId: item.rightId,
            rightRuleName: item.rightRuleName,
          };
        });

        console.log("this.ruleInfoList", this.ruleInfoList);
      }
    },

    // 成功回调
    onSuccess() {},

    // 验证-------------------------

    validatorConsumeCount(rule, value, callback) {
      const { consumeCount } = this.form;
      if (value === "" && consumeCount.isSelect === 1) {
        callback(new Error("不能为空"));
      } else if (consumeCount.isSelect === 0) {
        consumeCount.conditionValue = "";
        callback();
      } else {
        this.$vFN.Tools.validateStock(rule, value, callback);
      }
    },

    // 消费金额
    validatorConsumeAmount(rule, value, callback) {
      const { consumeAmount } = this.form;
      if (value === "" && consumeAmount.isSelect === 1) {
        callback(new Error("不能为空"));
      } else if (consumeAmount.isSelect === 0) {
        consumeAmount.conditionValue = "";
        callback();
      } else {
        this.$vFN.Tools.validateStock(rule, value, callback);
      }
    },

    // 充值次数
    validatorRechargeCount(rule, value, callback) {
      const { rechargeCount } = this.form;
      if (value === "" && rechargeCount.isSelect === 1) {
        callback(new Error("不能为空"));
      } else if (rechargeCount.isSelect === 0) {
        rechargeCount.conditionValue = "";
        callback();
      } else {
        this.$vFN.Tools.validateStock(rule, value, callback);
      }
    },

    // 充值金额
    validatorRechargeAmount(rule, value, callback) {
      const { rechargeAmount } = this.form;
      if (value === "" && rechargeAmount.isSelect === 1) {
        callback(new Error("不能为空"));
      } else if (rechargeAmount.isSelect === 0) {
        rechargeAmount.conditionValue = "";
        callback();
      } else {
        this.$vFN.Tools.validateStock(rule, value, callback);
      }
    },

    validate() {
      let that = this;
      return new Promise((resolve, reject) => {
        that.$refs["editForm"].validate((valid) => {
          if (valid) {
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
  },
  mounted() {
    this.init();
    if (this.type === "create") {
      this.loading = false;
      this.dialogTitle = "添加等级";
    } else {
      this.dialogTitle = "修改等级";
      this.getDetail();
    }
  },
};
</script>
